var editIndex = undefined, editTable = undefined, editTableRow = null, temId = 0;
// 常量
var constant = {
    server:{
        port: 8080,
        ip: (window.location.host).indexOf('localhost') >= 0 ?
                'http://localhost' : 'http://111.230.18.227',
    },
    style:{
        low:'?x-oss-process=style/oss-web-admin-low',
        mid:'?x-oss-process=style/oss-web-admin-mid',
        hd:'?x-oss-process=style/oss-web-admin-hd'
    },
    cache:{
        user: 'easy-admin-pc',
        token: 'easy-admin-pc-token'
    },
    route:{
        user:{
            login: '/v1/common/login',
            check: '/v1/common/check',
            base: '/v1/base/user',
            label: '/v1/base/user-label',
        },
        dict : {
            base: '/v1/sys/dict',
            module: '/v1/sys/dict-module',
            query: '/v1/sys/dict-by-code'
        },
        label: {
            base: '/v1/sys/label',
            group: '/v1/sys/label-group',
            module: '/v1/sys/label-module',
        },
        button: '/v1/sys/button',
        menu: '/v1/sys/menu',
        module: '/v1/sys/module',
        role: '/v1/sys/role',
        generator: '/v1/developer/generator',
        log: '/v1/sys/log',
        config: '/v1/sys/config',
    }
}
// 封装组件
var component = {
    /**
     * getSelectData    获取选中行数据
     * unselectAll      取消选中状态
     * resize           自适应表格
     * load             加载表格数据
     * getPager         获取分页组件对象
     * */
    datagrid:{
        getSelectData:function (_table) {
            var rows = $(_table).datagrid('getSelections');
            var data = [];
            for(var i=0; i<rows.length; i++){
                data.push(rows[i]);
            }
            return data;
        },
        getRowData:function (_table) {
            return $(_table).datagrid('getSelected');
        },
        getDataRow:function (_table) {
            return $(_table).datagrid('getRowIndex', $(_table).datagrid('getSelected'));
        },
        unselectAll:function (_table) {
            $(_table).datagrid('unselectAll');
        },
        resize:function (_table) {
            $(_table).datagrid('resize', {
                height:($('body').height()),
                width:($('body').width())
            });
        },
        load:function (_table, _json) {
            $(_table).datagrid('loadData', _json);
        },
        getPager:function (_table) {
            return $(_table).datagrid().datagrid('getPager');
        },
        init:function (_table, _param, _isResize) {
            var base = {
                fit:true,
                method:'get',
                title: '数据列表',
                rownumbers: false,
                striped:true,
                singleSelect:true,
                pagination: true,
                pageSize:20,
                fitColumns: true,
            };
            base = $.extend(base, _param);
            $(_table).datagrid(base);
            if((typeof _isResize) == 'undefined'){
                component.datagrid.resize(_table);
            }

        },
        append:function (_table, _json) {
            $(_table).datagrid('appendRow', _json);
        },
        updateRow:function (_table, _index, _json) {
            $(_table).datagrid('updateRow',{index: _index, row: _json});
            $(_table).datagrid('refreshRow', _index);
        },
        deleteRow:function (_table, _index) {
            $(_table).datagrid('deleteRow', _index);
        },
        all:function (_table) {
            return $(_table).datagrid('getRows');
        }
    },
    treegrid: {
        init:function (_table, _param, _isResize) {
            var base = {
                title: '数据列表',
                idField:'id',
                treeField:'name',
                lines: true,
                fitColumns: true,
            };
            base = $.extend(base, _param);
            $(_table).treegrid(base);
            if((typeof _isResize) == 'undefined'){
                component.treegrid.resize(_table);
            }
            kit.render(_table)
        },
        getRowData:function (_table) {
            return $(_table).treegrid('getSelected');
        },
        load:function (_table, _json) {
            $(_table).treegrid('loadData', _json);
        },
        append:function (_table, _json) {
            $(_table).treegrid('append', {
                parent: _json.parentId,
                data:[_json]
            });
        },
        insert:function (_table, _json, _row) {
            $(_table).treegrid('insert', {
                after: _row.id,
                data:_json
            });
        },
        find:function (_table, _id) {
            return $(_table).treegrid('find', _id);
        },
        updateRow:function (_table, _json) {
            $(_table).treegrid('update',{id: _json.id, row: _json});
        },
        delete:function (_table, _id) {
            $(_table).treegrid('remove', _id);
        },
        reload:function (_table) {
            $(_table).treegrid('reload');
        }
    },
    linkbutton:function (_id, _data) {
        var template = doT.template($('#linkbutton-template').text());
        $(_id).html(template(_data))
        kit.render(_id)
    },
    select:function (_id, _data) {
        var template = doT.template($('#select-option-template').text());
        $(_id).html(template(_data))
        kit.render(_id)
    },
    dialog:{
        init:function (_id, _param) {
            var base = {
                title: '',
                top:20,
                fit:false,
                draggable:false,
                closed: true,
                resizable: false,
                cache: false,
                modal: true,
            };
            base = $.extend(base, _param);
            $(_id).dialog(base);
        },
        open:function (_id) {
            $(_id).dialog('open');
        },
        close:function (_id) {
            $(_id).dialog('close')
        }
    },
    combobox:{
        init: function (_id, _data, _valueField, _textField) {
            var vf = (typeof _valueField) == 'undefined' ? 'code' : _valueField;
            var tf = (typeof _textField) == 'undefined' ? 'name' : _textField;
            $(_id).combobox({
                data: _data,
                valueField: vf,
                textField: tf,
                editable:false
            });
        },
        init2: function (_id, _data, _valueField, _textField) {
            var vf = (typeof _valueField) == 'undefined' ? 'code' : _valueField;
            var tf = (typeof _textField) == 'undefined' ? 'name' : _textField;
            $(_id).combobox({
                data: _data,
                valueField: vf,
                textField: tf,
                editable:false,
                multiple:true,
            });
        },
        setValue: function (_id, _value) {
            $(_id).combobox('setValue', _value);
        },
        setValues: function (_id, _values) {
            $(_id).combobox('setValues', _values);
        },
        getValue: function (_id) {
            $(_id).combobox('getValue');
        },
        getValues: function (_id) {
            $(_id).combobox('getValues');
        }
    },
    extend:{
        init:function () {
            $.extend($.fn.datagrid.methods, {
                addEditor : function(jq, param) {
                    if (param instanceof Array) {
                        $.each(param, function(index, item) {
                            var e = $(jq).datagrid('getColumnOption', item.field);
                            e.editor = item.editor;
                        });
                    } else {
                        var e = $(jq).datagrid('getColumnOption', param.field);
                        e.editor = param.editor;
                    }
                },
                removeEditor : function(jq, param) {
                    if (param instanceof Array) {
                        $.each(param, function(index, item) {
                            var e = $(jq).datagrid('getColumnOption', item);
                            e.editor = {};
                        });
                    } else {
                        var e = $(jq).datagrid('getColumnOption', param);
                        e.editor = {};
                    }
                },
                editCell: function(jq,param){
                    return jq.each(function(){
                        var opts = $(this).datagrid('options');
                        var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
                        for(var i=0; i<fields.length; i++){
                            var col = $(this).datagrid('getColumnOption', fields[i]);
                            col.editor1 = col.editor;
                            if (fields[i] != param.field){
                                col.editor = null;
                            }
                        }
                        $(this).datagrid('beginEdit', param.index);
                        for(var i=0; i<fields.length; i++){
                            var col = $(this).datagrid('getColumnOption', fields[i]);
                            col.editor = col.editor1;
                        }
                    });
                },
                datetimebox: {
                    init: function (container, options) {
                        var input = $('<input type="text" class="easyui-datetimebox">')
                            .appendTo(container);
                        //编辑框延迟加载
                        window.setTimeout(function () {
                            input.datetimebox($.extend({ editable: false }, options));
                        }, 10);
                        return input;
                    },
                    getValue: function (target) {
                        return $(target).datetimebox('getValue');
                    },
                    setValue: function (target, value) {
                        $(target).val(value);
                        window.setTimeout(function () {
                            $(target).datetimebox('setValue', value);
                        }, 150);
                    },
                    resize: function (target, width) {
                        var input = $(target);
                        if ($.boxModel == true) {
                            input.width(width - (input.outerWidth() - input.width()));
                        } else {
                            input.width(width);
                        }
                    }
                }
            });
        },
        endEditing:function () {
            if (editIndex == undefined){return true}
            if ($(editTable).datagrid('validateRow', editIndex)){
                $(editTable).datagrid('endEdit', editIndex);
                editIndex = undefined;
                return true;
            } else {
                return false;
            }
        },
        onClickCell:function (index, field) {
            if (component.extend.endEditing()){
                $(editTable).datagrid('selectRow', index)
                    .datagrid('editCell', {index:index,field:field});
                editIndex = index;
                var currentEdatagrid = $(this);
                var $input = $('.datagrid-editable .textbox,.datagrid-editable .datagrid-editable-input,.datagrid-editable .textbox-text');

                $input.focus();
                $input.bind('keydown', function(e){
                    var code = e.keyCode || e.which;
                    if(code == 13){
                        editTableRow = $(editTable).datagrid('getSelected');
                        $(currentEdatagrid).datagrid('acceptChanges');
                        $(currentEdatagrid).datagrid('endEdit', index);
                        var request = column.submit(editTableRow);
                        request.done(function (d) {
                            editTableRow['status'] = 1;
                            $(currentEdatagrid).datagrid('updateRow', {index: index, row: editTableRow});
                            $(currentEdatagrid).datagrid('refreshRow', index);
                        }).fail(function () {
                            editTableRow['status'] = 0;
                            $(currentEdatagrid).datagrid('updateRow', {index: index, row: editTableRow});
                            $(currentEdatagrid).datagrid('refreshRow', index);
                        })
                    }
                });
                $input.focusout(function () {
                    editTableRow = $(editTable).datagrid('getSelected');
                    $(currentEdatagrid).datagrid('acceptChanges');
                    $(currentEdatagrid).datagrid('endEdit', index);
                    editTableRow['status'] = 0;
                    $(currentEdatagrid).datagrid('updateRow', {index: index, row: editTableRow});
                    $(currentEdatagrid).datagrid('refreshRow', index);
                })
            }else{
                $(editTable).datagrid('selectRow', editIndex);
            }
        },
        remove:function () {
            $(editTable).datagrid('removeEditor', 'val');
        },
        add:function () {
            var row = $(editTable).datagrid('getSelected');
            switch (row.type){
                case 1:
                    $(editTable).datagrid('addEditor', {
                        field : 'val',
                        editor : {
                            type : 'text'
                        }
                    });
                    break;
                case 2:
                    $(editTable).datagrid('addEditor', {
                        field : 'val',
                        editor : {
                            type : 'numberbox'
                        }
                    });
                    break;
                case 3:
                    $("#table-list-label").datagrid('addEditor', {
                        field : 'val',
                        editor : {
                            type : 'datebox'
                        }
                    });
                    break;
                case 9:
                    $(editTable).datagrid('addEditor', {
                        field : 'val',
                        editor : {
                            type : 'combobox',
                            options : {
                                data: row.options,
                                valueField: 'val',
                                textField: 'txt',
                                editable: false,
                                required : true
                            }
                        }
                    });
                    break;
            }
        }
    }
}
// 基础工具
var kit = {
    // 组件渲染
    render:function (_id) {
        var $object = $(_id);
        $.parser.parse($object);
    },
    alert:function (_message, _icon) {
        // _icon => info\error\question\warning
        if((typeof _icon) == 'undefined'){
            _icon = '';
        }
        $.messager.alert('系统提示', _message, _icon);
    },
    confirm:function (_param) {
        $.messager.confirm(_param.title, _param.message, function(r){
            if (r){
                if((typeof _param.submit) != 'undefined'){
                    setTimeout(_param.submit, 10);
                }else{
                    kit.alert('没有可执行函数', 'warning');
                }
            }
        });
    },
    progress:{
        open:function () {
            $.messager.progress({
                text:'拼命处理中...',
            });
        },
        close:function () {
            $.messager.progress('close');
        }
    },
    form:{
        set:function (_id, _data) {
            _data['accept'] = true;
            $(_id).form('load', _data);
        },
        get:function (_id) {
            var $data = {};
            $.each($(_id).serializeArray(), function(i, field){
                $data[field.name] = field.value;
            });
            return $data;
        },
        validate:function (_id) {
            return $(_id).form('enableValidation').form('validate');
        },
        clean:function (_id) {
            var $data = kit.form.get(_id);
            for(var m in $data){
                $data[m] = '';
                if(m == 'sort'){
                    $data[m] = '0';
                }
                if(m == 'moduleId'){
                    $data[m] = '0';
                }
                if(m == 'parentId'){
                    $data[m] = '0';
                }

            }
            kit.form.set(_id, $data);
        }
    },
    wh: function(){
        var w = $('body').width();
        var h = $('body').height();
        return {width:w, height:h};
    },
    log:function (_message) {
        console.log(_message)
    },
    auth:function (_event) {
        var $fun = $(_event).attr('onclick');
        $fun = $fun.replace('(', '');
        $fun = $fun.replace(')', '');
        $fun = $fun.replace('this', '');
        $fun = $fun.replace(';', '');
    },
    getAttr: function (_id, _attr) {
        return $(_id).attr(_attr);
    },
    json:{
        update:function (_obj1,_obj2,_field) {
            var o = [];
            $.each(_obj1,function(i,obj)
            {
                if(obj[_field] == _obj2[_field]){
                    o.push(_obj2);
                }else{
                    o.push(obj);
                }
            });
            return o;
        },
        delete:function (_obj, _attr, _val) {
            var o = [];
            $.each(_obj,function(i,obj)
            {
                if(obj[_attr] != _val){
                    o.push(obj);
                }
            });
            return o;
        },
        attr2array:function (_obj, _attr) {
            var arr = [];
            $.each(_obj, function (index, obj) {
                kit.log(obj)
                arr.push(obj[_attr]);
            })
            return arr;
        }
    },
    time: {
        // 日期格式转时间戳
        date2timestamp:function (_date) {
            var timestamp = Date.parse(new Date(_date));
            return timestamp;
        },
        timestamp2shortdate:function (_date) {
            var date = new Date(parseInt(_date) * 1000);
            var short_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
            return short_date;
        },
        timestamp2time:function (_timestamp) {
            if(_timestamp > 0){
                var d = new Date(_timestamp * 1000);    // 根据时间戳生成的时间对象
                var date = (d.getFullYear()) + "-" +
                    kit.string.time((d.getMonth() + 1)) + "-" +
                    kit.string.time(d.getDate()) + " " +
                    kit.string.time(d.getHours()) + ":" +
                    kit.string.time(d.getMinutes()) + ":" +
                    kit.string.time(d.getSeconds());
                return date;
            }else{
                return '';
            }
        },
        checkDate:function (_date) {
            var result = _date.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
            if (result == null)
                return false;
            return true;
        }
    },
    string: {
        random:function (_len) {
            _len = _len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZ2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
            var maxPos = $chars.length;
            var ran = '';
            for (var i = 0; i < _len; i++) {
                ran += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return ran.toLowerCase();
        },
        cut:function (_str,_len) {
            var len = _str.length;
            if(len >_len){
                _str = _str.substring(0,_len)+'...';
            }
            return _str;
        },
        time:function (_str) {
            _str = _str.toString();
            if(_str.length == 1){
                return '0'+_str;
            }else{
                return _str;
            }
        }
    }
}
// 系统类
var sys = {
    exit:function () {
        store.clear();
        try{
            parent.exitSys()
        }catch (e){
            setTimeout(function () {
                window.location.href = '/';
            }, 3000)

        }
    }
}
// 网络工具
var http = {
    get:function (request) {
        request.method = 'get';
        return send(request);
    },
    post:function (request) {
        request.method = 'post';
        return send(request);
    },
    delete:function (request) {
        request.method = 'delete';
        return send(request);
    },
    put:function (request) {
        request.method = 'put';
        return send(request);
    },
    info:function (request) {
        request.method = 'info';
        return send(request);
    }
}
var token = store.get(constant.cache.token);
var header = {
    "Content-Type": "application/json; charset=utf-8",
    "token":(typeof token) == 'undefined' ? '' : token,
    "Access-Control-Allow-Origin":"*"
};
function send(request) {
    return $.ajax({
        type : request.method,
        url : constant.server.ip + ':' + constant.server.port + request.url,
        data: ajaxEmpty(request.data),
        async: typeof(request.async) == 'undefined' ? 'true' : request.async,
        contentType: "json",
        cache: false,
        headers: header,
        dataType:'json',
        beforeSend: function (xhr) {
            if(typeof(request.cl) == 'undefined')
                kit.progress.open();
        },
        statusCode: {
            200: function() {
                kit.progress.close();
            }
        },
        error:function(e){
            kit.progress.close();
            var res = e.responseJSON;
            var status = e.status;
            kit.log(res)
            switch (status){
                case 403:
                    kit.alert(res.message, 'error');
                    try{
                        if(res.isRefresh == 1){
                            setTimeout(sys.exit(), 3000);
                        }
                    }catch (e){}
                    break;
                case 406:
                    kit.alert(res.message, 'error');
                    setTimeout(sys.exit(), 3000);
                    break;
                case 411:
                    kit.alert(res.message, 'error');
                    setTimeout(sys.exit(), 3000);
                    break;
                default:
                    try{
                        kit.alert(res.message, 'error');
                    }catch(e){
                        kit.alert('服务器异常通讯失败', 'error');
                    }
            }

        }
    });
}
function ajaxEmpty(value) {
    if(typeof(value) == "undefined")
        return "";
    if(typeof(value) == "object")
        return JSON.stringify(value);
    return value;
}


var auth = {
    init: function () {
        var url = window.location.href;
        var btns = store.get('easy-admin-pc-btns');
        var data = [];
        $.each(btns, function (index, obj) {
            if(url.indexOf(obj.url) > -1){
                data = obj.btns;
            }
        })
        var tmpl = doT.template($("#linkbutton-template").text());
        $('#opt-auth-linkbutton').html(tmpl(data));
        kit.render('#opt-auth-linkbutton');
    },
    cache: function (_obj) {
        store.set('easy-admin-pc-token', _obj.token);
        store.set('easy-admin-pc-login-name', _obj.loginName);
        store.set('easy-admin-pc-menu', _obj.auth);
        store.set('easy-admin-pc-btns', _obj.btns);
        store.set('easy-admin-pc-label', _obj.label);
    },
}
